package com.LeeCode;

import java.util.HashMap;
import java.util.Map;

/**
 * 元素和为目标值的子矩阵数量
 */

public class Code1074 {
    public static void main(String[] args) {

    }

    public int numSubmatrixSumTarget(int[][] matrix, int target) {
        int m = matrix.length, n = matrix[0].length;
        int ans = 0;

        for (int i = 0; i < m; i++) {
            int[] colSum = new int[n];
            for (int i2 = i; i2 < m; i2++) {
                for (int j = 0; j < n; j++) {
                    colSum[j] += matrix[i2][j];
                }
                ans += subarraySum(colSum, target);
            }
        }
        return ans;
    }

    public int subarraySum(int[] nums, int target) {
        int ans = 0;
        int sum = 0;
        Map<Integer, Integer> map = new HashMap<>();
        map.put(0, 1);
        for (int num : nums) {
            sum += num;
            ans += map.getOrDefault(sum - target, 0);
            map.merge(sum, 1, Integer::sum);
        }
        return ans;
    }
}
